﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcWeb.Controllers
{
    public class RoleController : BaseController
    {
        // GET: /Role/
        public ActionResult Index(string id)
        {
            MvcWeb.ViewModels.Role.RoleModel viewModel = new ViewModels.Role.RoleModel();
            viewModel.aspnet_Roles = db.aspnet_Roles.ToList();

            if (!string.IsNullOrWhiteSpace(id))
            {
                Guid guid = new Guid(id);
                var model = db.aspnet_Roles.Find(guid);
                if (model != null)
                {
                    viewModel.RoleName = model.RoleName;
                    var arr = db.Role_Priviledges.Where(m => m.RoleId == model.RoleId).Select(m => m.Priviledge).ToArray();
                    viewModel.Privileges = string.Join(",", arr);
                }
            }

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Index(string id, MvcWeb.ViewModels.Role.RoleModel viewModel)
        {
            EAM.Model.aspnet_Roles model = null;
            if (string.IsNullOrWhiteSpace(id))
            {
                Roles.CreateRole(viewModel.RoleName);
            }
            else
            {
                Guid guid = new Guid(id);
                model = db.aspnet_Roles.Find(guid);
                db.aspnet_Roles.Attach(model);
                model.RoleName = viewModel.RoleName;
                model.LoweredRoleName = viewModel.RoleName.ToLower();
            }

            if (!string.IsNullOrWhiteSpace(viewModel.Privileges))
            {
                var list = db.Role_Priviledges.Where(m => m.RoleId == model.RoleId).ToList();
                foreach (var m in list)
                {
                    db.Role_Priviledges.Remove(m);
                }

                var arr = viewModel.Privileges.Split(',');
                foreach (var m in arr)
                {
                    db.Role_Priviledges.Add(new EAM.Model.Role_Priviledge()
                    {
                        RoleId = model.RoleId,
                        Priviledge = m
                    });
                }
            }

            db.SaveChanges();
            return RedirectToAction("index");
        }

        [HttpPost]
        public ActionResult Delete()
        {
            string ids = Request.Form["ids"];
            if (!string.IsNullOrWhiteSpace(ids))
            {
                string[] arr = ids.Split(',');
                foreach (var m in arr)
                {
                    Guid guid = new Guid(m);
                    var model = db.aspnet_Roles.Find(guid);
                    db.aspnet_Roles.Remove(model);
                }

                db.SaveChanges();
            }

            return Json(true);
        }
    }
}
